[3.14] gh-142831: Fix use-after-free in json encoder during re-entrant mutation (gh-142851)#150078
Open
ashm-dev wants to merge 1 commit into
Open
[3.14] gh-142831: Fix use-after-free in json encoder during re-entrant mutation (gh-142851)#150078ashm-dev wants to merge 1 commit into
ashm-dev wants to merge 1 commit into
Conversation
… mutation (pythongh-142851) User callbacks invoked during JSON encoding (e.g. the `default` callback or a custom string encoder) can mutate or clear the dict or sequence being encoded, invalidating borrowed references to items, keys, and values. Hold strong references unconditionally while iterating. Co-authored-by: Kumar Aditya <kumaraditya@python.org> Co-authored-by: Gregory P. Smith <greg@krypto.org> (cherry picked from commit 235fa72)
This was referenced May 19, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Manual backport of #142851 to 3.14 (the bot couldn't cleanly cherry-pick due to refactors in
main).The fix had to be adapted because in 3.14 the dict/list iteration loops were not yet extracted into the
_encoder_iterate_*_lock_heldhelpers introduced later inmain. Added thePy_INCREF/Py_DECREFaround each borrowed item/key/value inline inencoder_listencode_dict(both thePyMapping_ItemsandPyDict_Nextpaths) andencoder_listencode_list.The two regression tests from the original PR were cherry-picked as-is.
Built
--with-pydebugand ran./python -m test test_json -vlocally — all 218 tests pass.json.encodermapping iteration via re-entrant key encoder #142831